package cate.game.rank.cross;

import cate.common.table.activity.crossrankactivity.row.CrossRankActivityBaseRow;
import cate.common.table.activity.rankactivity.row.RankActivityRewardRow;
import cate.common.table.d.GDOperation;
import cate.game.GameBody;
import cate.game.framework.ModuleMan;
import cate.game.mail.po.MailBuilder;
import cate.game.rank.po.Rank;
import cate.game.res.MixRes;
import cate.game.role.mail.Mail;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CrossRankRecvModule extends ModuleMan {

    @Override
    public void initDependent() throws Exception {

    }

    @Override
    public void initIndependent(GameBody game) throws Exception {
        super.initIndependent(game);
        game.rpcRecv().onRequestResponseTemplate(CrossRankMsg.GAME_SETTLE_ACT, CrossRankMessageModule.CrossRankSettle.class, (head, req) -> this.settle(game, req));
    }

    private Map<Integer, Rank> settle(GameBody game, CrossRankMessageModule.CrossRankSettle settle) {
        CrossRankActivityBaseRow baseRow = game.table.crossRankActivity.base.get(settle.configTid);
        if (baseRow == null || baseRow.mailId == 0) {
            return settle.indexToRoleRank;
        }
        Map<Integer, Rank> failMap = new HashMap<>();
        settle.indexToRoleRank.forEach((index, rank) -> {
            RankActivityRewardRow rewardRow = game.table.crossRankActivity.reward.getRewardRow(baseRow.group, index);
            if (rewardRow != null && StringUtils.isNotBlank(rewardRow.rewardStr)) {
                if (rank != null) {
                    MixRes reward = new MixRes(rewardRow.rewardStr);
                    if (StringUtils.isNotBlank(rewardRow.extraRewardStr) && rank.value >= rewardRow.extraValue) {
                        reward.addList(new MixRes(rewardRow.extraRewardStr));
                    }
                    List<Object> params = new ArrayList<>();
                    params.add(index);
                    Mail mail = new MailBuilder()
                            .setContentId(baseRow.mailId)
                            .setParamList(params)
                            .setReward(reward)
                            .setOperation(GDOperation.RANK_ACTIVITY_REWARD)
                            .setOperationSub(index)
                            .build();
                    log.info("跨服排行榜活动{}发送邮件，第{}名:{}, value:{}", baseRow.funcId, index, rank.owner.base.name, rank.value);
                    game.mail.send(rank.owner.uid, mail);
                }
            } else {
                failMap.put(index, rank);
            }
        });
        return failMap;
    }
}
